use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpListener;
use tokio::sync::mpsc;

#[tokio::main]
async fn main() {
    let listener = TcpListener::bind("127.0.0.1:8080").await.unwrap();

    let mut last_channel = None;

    loop {
        let (mut socket, addr) = listener.accept().await.unwrap();
        let mut the_other_half_channel = None;
        if last_channel.is_none() {
            let mut channel1 = mpsc::channel(2);
            let mut channel2 = mpsc::channel(2);

            last_channel = Some((channel1.0, channel2.1));
            the_other_half_channel = Some((channel2.0, channel1.1));
        }


	let (tx, mut rx) = last_channel.unwrap();

        tokio::spawn(async move {
            let (mut reader, mut writer) = socket.split();

            let mut reader = BufReader::new(reader);
            let mut line = String::new();

            loop {
                tokio::select! {

                    result = reader.read_line(&mut line) => {
                    let bytes_read = result.unwrap();
                        if bytes_read == 0 || line.trim() == "quit" {
                            break;
                        }

			tx.send(line.clone()).await.unwrap();
                        line.clear();

                    }

		    result = rx.recv() => {
			let msg : String = result.unwrap();
                        writer.write_all(msg.as_bytes()).await.unwrap();
		    }



                };

            }
        });

        if !the_other_half_channel.is_none() {
            last_channel = the_other_half_channel;
        } else {
            last_channel = None;
        }
    }
}
